<?php
class Message extends AppModel {

	var $validate = array(
		'to' => array(
			'notempty' => array(
				'rule' => 'notempty',
				'message' => 'adgsdgsg',
			),
		),
		'subject' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'dsgsdg',
			),
		),
		'body' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'sdgsdgsg',
			),
		),
	);
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
	
	var $order = array('Message.created' => 'DESC');
	
	var $actsAs = array('Containable');
	
	// get the inbox
	function get_inbox($username = null) {
		if ($username == null) {
			return false;
		} else {
			$conditions = array(
				'Message.to_user' => $username,
				'NOT' => array(
					array('Message.receiver_deleted' => 1),
				)
			);
			$messages = $this->find('all', array('conditions' => $conditions, 'contain' => array('User')));
			return $messages;
		}
	}
	
	// send a message
	function send($data = null) {
		if ($data == null) {
			return false;
		} else {
			// get user
			$user = $this->User->find('first', array('conditions' => array('User.username' => $data['Message']['to']), 'fields' => array('User.id', 'User.username')));
			if (isset($user['User']['id'])) {
				// if no parent_id, then it is 0
				if ($data['Message']['parent_id'] == null) {
					$data['Message']['parent_id'] = 0;
				} else {
					// if parent_id then get parent
					$parent = $this->read(null, $data['Message']['parent_id']);
					// if someone has already deleted the parent then reply in a new conversation
					if ($parent['Message']['receiver_deleted'] == 1 or $parent['Message']['sender_deleted'] == 1) {
						$data['Message']['parent_id'] = 0;
					}
				}
				$data['Message']['to_user'] = $data['Message']['to'];
				return $this->saveMy($data);
			} else {
				return false;
			}
		}
	}
	
	// get the data needed to send a reply
	function get_reply_data($message_id = null) {
		if ($message_id == null) {
			return false;
		} else {
			$message = $this->read(null, $message_id);
			if ($message['Message']['to_user'] == $_SESSION['Auth']['User']['username']) {
				if ($message['Message']['parent_id'] == 0)
					$replydata['Message']['parent_id'] = $message['Message']['id'];
				else
					$replydata['Message']['parent_id'] = $message['Message']['parent_id'];
				$replydata['Message']['to'] = $message['User']['username'];
				$replydata['Message']['subject'] = 'RE: ' . $this->remove_re($message['Message']['subject']);
				return $replydata;
			} else {
				return false;
			}
		}
	}
	
	// function to remove the extra RE: when replying to a message
	function remove_re($str = null) {
		if ($str == null) {
			return false;
		} elseif ($i = strrpos($str, ':')) {
			$len = strlen($str) - $i;
			$str = substr($str, $i+2, $len);
			return $str;
		} else {
			return $str;
		}	
	}

	// This function retrieves the conversation that belongs to the given message
	function get_conversation($message_id = null) {
		if ($message_id == null) {
			return false;
		} else {
			// build the first set of conditions, check if user is sender or receiver and wether the user has deleted the message or not
			$conditions = array(
				'OR' => array(
					array(
						'Message.to_user' => $_SESSION['Auth']['User']['username'],
						'NOT' => array(
							'Message.receiver_deleted' => 1
						)
					),
					array(
						'Message.user_id' => $_SESSION['Auth']['User']['id'],
						'NOT' => array(
							'Message.sender_deleted' => 1
						)
					)
				)
			);
			// get the message that belongs to the message_id parameter
			$message = $this->read(null, $message_id);
			// if not read, mark as read
			$read = $this->mark_as_read($message);
			// build the second set of conditions, check wether the message has a parent or not
			// message has parent
			if ($message['Message']['parent_id'] != 0) {
				// get messages where parent_id or id is the parent_id of the selected message
				$secondconditions = array(
					'AND' => array(
						'OR' => array(
							array('Message.parent_id' => $message['Message']['parent_id']),
							array('Message.id' => $message['Message']['parent_id'])
						)
					)
				);
			} else { // message has no parent
				// get messages where parent_id or id is the given parameter
				$secondconditions = array(
					'AND' => array(
						'OR' => array(
							array('Message.parent_id' => $message_id),
							array('Message.id' => $message_id)
						)
					)
				);
			}
			// merge conditions
			$conditions = array_merge($conditions, $secondconditions);
			$order = array(
				'Message.parent_id' => 'ASC',
				'Message.created' => 'ASC'
			);
			// get the conversation
			if ($message = $this->find('all', array('conditions' => $conditions, 'order' => $order, 'contain' => array('User' => array('ContractorProfile', 'DesignerProfile'))))) {
				return $message;
			} else {
				return false;
			}
		}
	}
	
	// function to mark a message as read
	// takes a array with message data (minimum required fields: id and read)
	function mark_as_read($message = null) {
		if ($message == null) {
			return false;
		} else {
			if ($message['Message']['read'] == 0) {
				$message['Message']['read'] = 1;
				return $this->save($message);
			}
		}
	}
	
	// function which deletes conversation that belongs to the given message
	function delete_conversation($message_id = null) {
		if ($message_id ==  null) {
			return false;
		} else {
			// get the complete message
			$message = $this->read(null, $message_id);
			// check wether the message is a parent or a child and build the conditions
			if ($message['Message']['parent_id'] != 0) {
				$conditions = array(
					'OR' => array(
						array('Message.parent_id' => $message['Message']['parent_id']),
						array('Message.id' => $message['Message']['parent_id'])
					)
				);
			} else {
				$conditions = array(
					'OR' => array(
						array('Message.parent_id' => $message['Message']['id']),
						array('Message.id' => $message['Message']['id'])
					)
				);
			}
			// with the conditions all the messages in the conversation are found
			$messages = $this->find('all', array('conditions' => $conditions));
			// loop through the messages
			foreach($messages as $message) {
				// if a message is a received message, set receiver_deleted. Else set sender_deleted
				if ($message['Message']['to_user'] == $_SESSION['Auth']['User']['username'])
					$message['Message']['receiver_deleted'] = 1;
				elseif ($message['Message']['user_id'] == $_SESSION['Auth']['User']['id'])
					$message['Message']['sender_deleted'] = 1;
				else
					return false;
				// save the message
				$this->save($message);
			}
			return true;
		}
	}
	
	// function which returns number of unread messages
	function get_not_read() {
		$not_read_count = $this->find('count', array('conditions' => array('Message.to_user' => $_SESSION['Auth']['User']['username'], 'Message.read' => 0)));
		return $not_read_count;
	}

}
?>
